<template>
    <n-upload
        :headers="props.headers"
        :action="props.uploadUrl"
        :max="props.max"
        v-model:file-list="fileList"
        @remove="uploadRemove"
        @finish="uploadSuccess"
        @before-upload="uploadBefore"
        list-type="image-card">点击上传</n-upload>
</template>
<script setup lang="ts">
import {ref, defineEmits, defineProps, onMounted} from 'vue';
import { getImageUrl } from "@/utils/wish";

const emit = defineEmits<{
    (e: 'value-change', event: any): any;
}>();
const fileList = ref<any>();
const props = defineProps({
    // 用来回显的数据，数据库存储以,连接
    value: String,
    // 最大上传数
    max: {
        type: Number,
        default: 3
    },
    // 限制类型
    type: {
        type: Array,
        default: () => {
            return ['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'image/svg+xml'];
        }
    },
    // 上传大小限制M
    maxSize: {
        type: Number,
        default: 5
    },
    // 上传地址
    uploadUrl: {
        type: String,
        default: import.meta.env.VITE_APP_BASE_API + '/upload/image'
    },
    headers: {
        type: Object,
        default: () => ({
            token: localStorage.getItem('token')
        })
    }
});
let imgList: any[] = [];
// 加载获取传递文件
onMounted(() => {
    if (props.value) {
        let arr = props.value.split(',').map((i: string) => {
            return {
                url: getImageUrl(i),
                id: i,
                resUrl: i,
                name: i.substring(i.lastIndexOf('/') + 1),
                status: 'finished'
            }
        });
        // 让上传组件受控回显
        fileList.value = arr;
        // 绑定回复调用方的值
        imgList = arr;
    }
});
/**
 * 文件上传之前
 * @param file
 */
const uploadBefore = ({ file }: any) => {
    const { maxSize, type } = props;
    if (maxSize && file.file.size / 1024 / 1024 > maxSize) {
        window.$message.warning(`图片文件不能超过${maxSize}M`)
        return false;
    }
    if (type && type.length) {
        if (!type.includes(file.file.type)) {
            window.$message.warning(`只能上传类型为${type}的图片`)
            return false;
        }
    }
}

/**
 * 图片删除事件
 */
const uploadRemove = ({file}: any) => {
    for (let i = 0; i < imgList.length; i++) {
        if (imgList[i].id === file.id) {
            imgList.splice(i, 1);
        }
    }
    emit('value-change', imgList.map((i :any) => (i.resUrl)));
}

/**
 *  上传成功钩子函数
 *  eval：函数计算，并将内容执行为脚本代码
 */
const uploadSuccess = ({file, event}: any) => {
    if (event && event.target && event.target.response) {
        const res = eval(`(${event.target.response})`)
        if (res.code === 200) {
            // 设置文件对象浏览路径
            imgList.push({
                ...file,
                resUrl: res.data
            });
            emit('value-change', imgList.map((i :any) => (i.resUrl)));
        } else {
            window.$message.error(res.message);
        }
    }
}
</script>
<style lang="scss" scoped>
</style>
